<template>
   <div class="app-container">
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
         <el-form-item label="公司名称" prop="name">
            <el-input
               v-model="queryParams.name"
               placeholder="请输入公司名称"
               clearable
               style="width: 200px"
               @keyup.enter="handleQuery"
            />
         </el-form-item>
         <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="部门状态" clearable style="width: 200px">
               <el-option
                  v-for="dict in sys_company_disable"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
               />
            </el-select>
         </el-form-item>
         <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
         </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
         <el-col :span="1.5">
            <el-button
               type="primary"
               plain
               icon="Plus"
               @click="handleAdd"
               v-hasPermi="['system:company:add']"
            >新增</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button
               type="info"
               plain
               icon="Sort"
               @click="toggleExpandAll"
            >展开/折叠</el-button>
         </el-col>
         <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table
         v-if="refreshTable"
         v-loading="loading"
         :data="deptList"
         row-key="id"
         :default-expand-all="isExpandAll"
         :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
         <el-table-column prop="name" label="公司名称" width="260"></el-table-column>
         <el-table-column prop="level" label="等级" width="200">
<!--           <template #default="scope">-->
<!--            -->
<!--           </template>-->
         </el-table-column>
         <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
               <dict-tag :options="sys_company_disable" :value="scope.row.status" />
            </template>
         </el-table-column>
         <el-table-column label="创建时间" align="center" prop="createTime" width="200">
            <template #default="scope">
               <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
         </el-table-column>
         <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">

              <el-button link type="primary" v-if="scope.row.level == 1 || scope.row.level == 2" icon="Edit" @click="merchantUpdate(scope.row)" v-hasPermi="['system:company:merchant']">商户配置</el-button>
               <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:company:edit']">修改</el-button>
               <el-button v-if="scope.row.level != 3" link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['system:company:add']">新增</el-button>
              <el-button v-if="scope.row.level == 3" link type="primary" icon="EditPen" @click="regionUpdate(scope.row)" v-hasPermi="['system:company:region']">设置区长</el-button>
            </template>
         </el-table-column>
      </el-table>
     <!-- 商户配置 -->
     <el-dialog title="设置区长" v-model="regionOpen" width="400px" append-to-body>
       <el-form ref="deptRef" :model="regionForm" :rules="regionRules" label-width="80px">
         <el-row>
           <el-col :span="24">
             <el-form-item label="区长" prop="regionName">
               <el-input v-model="regionForm.regionName" placeholder="请输入区长名称"/>
             </el-form-item>
           </el-col>

         </el-row>
       </el-form>
       <template #footer>
         <div class="dialog-footer">
           <el-button type="primary" @click="submitRegion">确 定</el-button>
           <el-button @click="cancel">取 消</el-button>
         </div>
       </template>
     </el-dialog>
      <!-- 商户配置 -->
      <el-dialog title="商户配置" v-model="merchantOpen" width="600px" append-to-body>
         <el-form ref="deptRef" :model="merchantForm" :rules="merchantRules" label-width="110px">
            <el-row>
               <el-col :span="12">
                  <el-form-item label="商户号" prop="merchantId">
                    <el-input v-model="merchantForm.merchantId" placeholder="请输入商户号"/>
                  </el-form-item>
               </el-col>
              <el-col :span="12" v-if="!isLevel">
                <el-form-item label="收款账号" prop="accountNo">
                  <el-input v-model="merchantForm.accountNo" placeholder="请输入收款账号"/>
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="!isLevel">
                <el-form-item label="收款账户名" prop="accountName">
                  <el-input v-model="merchantForm.accountName" placeholder="请输入收款账户名"/>
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="isLevel">
                <el-form-item label="证书密码" prop="merchantPwd">
                  <el-input v-model="merchantForm.merchantPwd" placeholder="请输入证书密码"/>
                </el-form-item>
              </el-col>
              <el-col :span="24" v-if="isLevel">
                <el-form-item label="商户名称" prop="merchantName">
                  <el-input v-model="merchantForm.merchantName" placeholder="请输入商户名称"/>
                </el-form-item>
              </el-col>
              <el-col :span="24" v-if="isLevel">
                <el-form-item label="商户路径地址" prop="merchantPfx">
                  <el-upload
                      class="upload-demo"
                      accept=".pfx"
                      :limit="1"
                      :headers="upload.headers"
                      :action="upload.url"
                      :on-success="handleChange"
                      :on-error	="handleError">
                    <el-button size="small" type="primary">点击上传</el-button>
                    <template #tip>
                      <div class="el-upload__tip">只能上传.pfx文件</div>
                    </template>
                  </el-upload>
                  <el-input v-if="merchantForm.merchantPfx" v-model="merchantForm.merchantPfx" placeholder="请输入商户路径地址"/>
                </el-form-item>
              </el-col>

            </el-row>
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitMerchant">确 定</el-button>
               <el-button @click="cancel">取 消</el-button>
            </div>
         </template>
      </el-dialog>
     <!-- 添加或修改部门对话框 -->
     <el-dialog :title="title" v-model="open" width="600px" append-to-body>
       <el-form ref="deptRef" :model="form" :rules="rules" label-width="80px">
         <el-row>
           <el-col :span="24" v-if="form.parentId !== 0">
             <el-form-item label="上级部门" prop="parentId">
               <el-tree-select
                   v-model="form.parentId"
                   :data="deptOptions"
                   :props="{ value: 'id', label: 'name', children: 'children' }"
                   value-key="id"
                   placeholder="选择上级部门"
                   check-strictly
               />
             </el-form-item>
           </el-col>
           <el-col :span="12">
             <el-form-item label="名称" prop="name">
               <el-input v-model="form.name" placeholder="请输入名称"/>
             </el-form-item>
           </el-col>
           <el-col :span="12">
             <el-form-item label="等级" prop="level">
               <el-select v-model="form.level" placeholder="请选择等级">
                 <el-option label="集团" value="1"></el-option>
                 <el-option label="分公司" value="2"></el-option>
                 <el-option label="区域门店" value="3"></el-option>
               </el-select>
             </el-form-item>
           </el-col>
           <el-col :span="12">
             <el-form-item label="排序" prop="sort">
               <el-input-number v-model="form.sort" controls-position="right" :min="0"/>
             </el-form-item>
           </el-col>
           <el-col :span="12">
             <el-form-item label="状态">
               <el-radio-group v-model="form.status">
                 <el-radio
                     v-for="dict in sys_company_disable"
                     :key="dict.value"
                     :value="dict.value"
                 >{{ dict.label }}</el-radio>
               </el-radio-group>
             </el-form-item>
           </el-col>
           <el-col :span="12">
             <el-form-item label="备注" prop="leader">
               <el-input type="textarea" v-model="form.remark" placeholder="请输入备注" maxlength="200" />
             </el-form-item>
           </el-col>
         </el-row>
       </el-form>
       <template #footer>
         <div class="dialog-footer">
           <el-button type="primary" @click="submitForm">确 定</el-button>
           <el-button @click="cancel">取 消</el-button>
         </div>
       </template>
     </el-dialog>
   </div>
</template>

<script setup name="Dept">
import {
  listDept,
  getDept,
  addDept,
  updateDept,
  listDeptExcludeChild,
  addMerchantConfig,
  showMerchantConfig, setRegionName
} from "@/api/company/companyFramework"
import {getToken} from "@/utils/auth.js";

const { proxy } = getCurrentInstance()
const { sys_company_disable } = proxy.useDict("sys_company_disable")

const deptList = ref([])
const open = ref(false)
const isLevel = ref(true)
const merchantOpen = ref(false)
const regionOpen = ref(false)

const loading = ref(true)
const showSearch = ref(true)
const title = ref("")
const deptOptions = ref([])
const isExpandAll = ref(true)
const refreshTable = ref(true)
const upload = reactive({

  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/common/upload"
})
const data = reactive({
  form: {},
  regionForm:{
    regionName:undefined
  },
  merchantForm:{},
  queryParams: {
    name: undefined,
    status: undefined
  },
  rules: {
    parentId: [{ required: true, message: "上级部门不能为空", trigger: "blur" }],
    name: [{ required: true, message: "公司名称不能为空", trigger: "blur" }],
    sort: [{ required: true, message: "显示排序不能为空", trigger: "blur" }],
    level: [{ required: true, message: "等级不能为空", trigger: "blur" }],
    levelType: [{ required: true, message: "等级类型不能为空", trigger: "blur" }]
  },
  regionRules:{
    regionName: [{ required: true, message: "区长名称不能为空", trigger: "blur" }],
  },
  merchantRules:{
    merchantId: [{ required: true, message: "商户号不能为空", trigger: "blur" }],
    accountNo: [{ required: true, message: "收款账号不能为空", trigger: "blur" }],
    accountName: [{ required: true, message: "收款账户名不能为空", trigger: "blur" }],
    merchantPwd: [{ required: true, message: "证书密码不能为空", trigger: "blur" }],
    merchantPfx: [{ required: true, message: "商户路径地址不能为空", trigger: "blur" }],
    merchantName: [{ required: true, message: "商户名称不能为空", trigger: "blur" }],
  }
})

const { queryParams, form, merchantForm,rules,merchantRules,regionForm,regionRules} = toRefs(data)

/** 查询部门列表 */
function getList() {
  loading.value = true
  listDept(queryParams.value).then(response => {
    deptList.value = proxy.handleTree(response.data, "id")
    loading.value = false
  })
}

/** 取消按钮 */
function cancel() {
  open.value = false
  merchantOpen.value = false
  regionOpen.value = false
  reset()
}

/** 表单重置 */
function reset() {
  form.value = {
    id: undefined,
    parentId: undefined,
    name: undefined,
    level: '',
    levelType: undefined,
    sort: undefined,
    status: "1",
    remark: undefined

  }
  proxy.resetForm("deptRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

/** 新增按钮操作 */
function handleAdd(row) {
  reset()
  listDept().then(response => {
    deptOptions.value = proxy.handleTree(response.data, "id")
  })
  if (row != undefined) {
    form.value.parentId = row.id
  }
  open.value = true
  title.value = "添加部门"
}

/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false
  isExpandAll.value = !isExpandAll.value
  nextTick(() => {
    refreshTable.value = true
  })
}
/*商城证书*/
function handleChange(e){
  console.log(e)
 merchantForm.value.merchantPfx = e.fileName;

}
function handleError(e){
  console.log(e)
}
//设置区长
function regionUpdate(row){
  regionForm.value.id = row.id;
  regionForm.value.regionName = row.regionName;

  regionOpen.value = true

}
/*商户配置*/
function merchantUpdate(row){
  console.log(row.level)
  if(row.level == 1){
    isLevel.value = true;
  }else {
    isLevel.value = false;
  }
  showMerchantConfig(row.id).then(response => {
    console.log(response)
    merchantForm.value = response.data;
    // merchantForm.value.companyId = row.id
    merchantOpen.value = true
  })

  // title.value = "商户配置"
}
//设置区长的提交
function submitRegion(){
  proxy.$refs["deptRef"].validate(valid => {
    if (valid) {
      // merchantForm
      setRegionName(regionForm.value).then(response => {
        proxy.$modal.msgSuccess("设置成功")
        regionOpen.value = false
        regionForm.value = {};
        getList()
      })

    }
  })
}

/** 提交按钮 */
function submitMerchant() {
  proxy.$refs["deptRef"].validate(valid => {
    if (valid) {
      // merchantForm
      addMerchantConfig(merchantForm.value).then(response => {
        proxy.$modal.msgSuccess("配置成功")
        merchantOpen.value = false
        merchantForm.value = {};
        getList()
      })

    }
  })
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  listDeptExcludeChild(row.id).then(response => {
    deptOptions.value = proxy.handleTree(response.data, "id")
  })
  getDept(row.id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改部门"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["deptRef"].validate(valid => {
    if (valid) {
      if (form.value.id != undefined) {
        updateDept(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {

        addDept(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}


getList()
</script>
